<?php
namespace app\admin\Model;

use think\Model;
use Think\Upload;

class Picture extends Model {
    protected $_auto = array(
        array('status', 1, self::MODEL_INSERT),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
    );
	// 上传
    public function upload($files, $setting, $driver = 'local', $config = null) {
        $setting['callback'] = array($this, 'isFile');
		$setting['removeTrash'] = array($this, 'removeTrash');
        $Upload = new Upload($setting, $driver, $config);

        foreach ($files as $key => $file) {
            $ext = strtolower($file['ext']);
            if ( in_array($ext, array('jpg','jpeg','bmp','png')) ) hook('dealPicture',$file['tmp_name']);
        }

        $info   = $Upload->upload($files);

        if ( $info ) { // 文件上传成功，记录文件信息
            foreach ( $info as $key => &$value ) {
                if(isset($value['id']) && is_numeric($value['id']) ) continue;
                if(strtolower($driver)=='sae'){
                    $value['path'] = $config['rootPath'].'Picture/'.$value['savepath'].$value['savename']; //在模板里的url路径
                }else{
                    if(strtolower($driver) != 'local'){
                        $value['path'] =$value['url'];
                    }
                    else{
                        $value['path'] = (substr($setting['rootPath'], 1).$value['savepath'].$value['savename']);	//在模板里的url路径
                    }

                }

                $value['type'] = $driver;

                if($this->create($value) && ($id = $this->add())){
                    $value['id'] = $id;
                } else {
                    unset($info[$key]);
                }
            }

            foreach($info as &$t_info){
                if($t_info['type'] =='local'){
                    $t_info['path']=get_pic_src($t_info['path']);
                } else {
                    $t_info['path']=$t_info['path'];
                }
            }
            return $info; //文件上传成功
        } else {
            $this->error = $Upload->getError();
            return false;
        }
    }
	// 下载指定
    public function download($root, $id, $callback = null, $args = null){
        $file = $this->find($id);
        if(!$file){
            $this->error = L('_NO_THIS_FILE_IS_NOT_THERE_WITH_EXCLAMATION_');
            return false;
        }

        /* 下载文件 */
        switch ($file['location']) {
            case 0: // 下载本地文件
                $file['rootpath'] = $root;
                return $this->downLocalFile($file, $callback, $args);
            case 1: // 下载远程FTP文件
                break;
            default:
                $this->error = L('_UNSUPPORTED_FILE_STORAGE_TYPE_WITH_EXCLAMATION_');
                return false;
        }
    }
	// 检测当前上传的文件是否已经存在
    public function isFile($file){
        if(empty($file['md5']) ) throw new \Exception('缺少参数:md5');
		$map = array('md5' => $file['md5'],'sha1'=>$file['sha1'],);
        return $this->field(true)->where($map)->find();
    }
	// 下载本地
    private function downLocalFile($file, $callback = null, $args = null){
        if(is_file($file['rootpath'].$file['savepath'].$file['savename'])){
            /* 调用回调函数新增下载数 */
            is_callable($callback) && call_user_func($callback, $args);

            /* 执行下载 */ //TODO: 大文件断点续传
            header("Content-Description: File Transfer");
            header('Content-type: ' . $file['type']);
            header('Content-Length:' . $file['size']);
            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
                header('Content-Disposition: attachment; filename="' . rawurlencode($file['name']) . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
            }
            readfile($file['rootpath'].$file['savepath'].$file['savename']);
            exit;
        } else {
            $this->error = L('_FILE_HAS_BEEN_DELETED_WITH_EXCLAMATION_');
            return false;
        }
    }
	// 清除数据库存在但本地不存在的数据
	public function removeTrash($data){
		$this->where(array('id'=>$data['id'],))->delete();
	}
}